﻿@model IEnumerable<RH.Web.ViewModels.ProductImageViewModel>
@using RH.Web.Utility;
@using RH.Common.Extensions;
@using RH.Common.DB;
@using RH.Web.ViewModels;

@{
    Layout = "~/Views/Shared/_PopupLayout.cshtml";
    ViewBag.Title = Html.GetPageTitle("Add Remove Product Images");
    int _ProductID = ViewBag.ProductID;
    int _ProductImageID = Convert.ToInt32(ViewBag.ProductImageID);
    ProductViewModel product = ViewBag.Product as ProductViewModel;
    String _Info = product == null ? String.Empty : product.Name;
    String _TempUploadedImageUrl = ViewBag.CropBoxImageUrl;// == null ? String.Empty : NullHandler.GetString(ViewBag.CropBoxImageUrl);
}
@*<div class="page-heading" style="padding-top:0px; padding-left:0px; margin-bottom:0px;">
    <h1>Manage Product Images</h1>
    <div>
        You can upload maximum @ConfigReader.MaxNumberOfProductImages images for @_Info.        
    </div>
</div>*@
<div class="rh-page-body">
    @if (product == null)
    {
        @Html.ErrorMessageBox("Sorry! Requested Product does not exist.")
    }
    else
    {   
        <table class="rh-crop-table" cellpadding="0" cellspacing="0">
            <colgroup>
                <col style="width:17%;" />
                <col style="width:64%;" />
                <col />
            </colgroup>

            <tr>
                @*Left Column*@
                <td>
                    <div id="divThumbContainer" class="rh-top-5px">
                        @foreach (RH.Web.ViewModels.ProductImageViewModel image in Model)
                        {
                            <div class="rh-thumb-container">
                                <div class="pull-left">
                                    @*<a href="javascript:void(0);" onclick="ConformDeleteDialog(@image.ID, this);" title="Click to Delete this Product Image.">*@
                                    @Html.ProductThumb(image, this.Url, image.Picture)
                                    @*</a>*@
                                </div>
                                <div class="pull-left">
                                    <button class="btn btn-danger btn-sm" onclick="ConformDeleteDialog(@image.ID, this);" title="Click to Delete this Image."><i class="glyphicon glyphicon-remove"></i> </button>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                        }
                    </div>
                    <div id="divPosition"></div>
                </td>

                @*Middle Column*@
                <td class="rh-border-right">
                    <form id="frmProductImage" action="@Url.Action("List")" method="post" enctype="multipart/form-data" class="form-group">                        
                        <div id="trUploadControls" @{if (!_TempUploadedImageUrl.IsNullOrEmpty()) { <text> style="display:none;" </text> }}>                            
                            <div class="rh-top-5px">
                                <input id="fileProductImage" type="file" name="productImage" onchange="ValidateUpload();" class="hidden" />
                                <div class="input-group">
                                    <input id="ProductImage_Cosmetic" class="form-control" type="text" placeholder="Select a Picture" />
                                    <div class="input-group-btn pull-left">
                                        <a class="btn btn-default" onclick="$('#fileProductImage').click();"><i class="glyphicon glyphicon-folder-open"></i> Browse</a>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            <div id="divInfoMessage" class="rh-top-5px">
                                @if (ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] != null) {
                                    @Html.ErrorMessageBox(ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] as String)
                                }
                                else if (Model != null && Model.Count() >= ConfigReader.MaxNumberOfProductImages) {
                                    @Html.WarningMessageBox(String.Format("Sorry! You cannot upload more than {0} images for a property.", ConfigReader.MaxNumberOfProductImages))
                                }
                            </div>                            
                            <input type="hidden" name="hdnWidthHeight" id="hdnWidthHeight" value="@ViewBag.WidthHeight" />
                            <input type="hidden" name="productID" id="productID" value="@_ProductID" />
                            <input type="hidden" id="hdnCoordinates" value="" />
                            <input type="hidden" id="hdnProductImageID" name="productImageID" value="@_ProductImageID" />
                            <input type="hidden" id="hdnOriginalFileName" value="@ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME]" />
                        </div>
                        
                        <div id="divCropBoxContainer" class="rh-top-5px">                    
                            <img id="imgCropBox" src="@_TempUploadedImageUrl" alt="" @{if (_TempUploadedImageUrl.IsNullOrEmpty()){ <text>style="display:none;"</text>}}/>
                        </div>
                        
                    </form>       
                </td>
                @*Right Column*@
                <td>
                    <div class="rh-border-left rh-top-5px" style="overflow: hidden; width:140px; height:105px;"> @*Inline styles in thid div element is required for image cropper preview winodw*@
                        <img id="imgPreview" class="jcrop-preview" src="@ViewBag.CropBoxImageUrl" alt="" />
                    </div>
                    @if (!_TempUploadedImageUrl.IsNullOrEmpty()) {
                        <div id="divButtons" class="rh-top-5px">
                            <button id="btnSave" type="button" class="btn btn-primary btn-sm" onclick="CropAndSaveImage();"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
                            <button id="btnCancel" type="button" class="btn btn-sm" onclick="CancelImageCrop();"><i class="glyphicon glyphicon-thumbs-down"></i> Cancel</button>
                        </div>
                    }
                </td>
            </tr>
        </table>
        
        @*<div id="dialog" style="display:none;"></div>*@
        @*Delete Confirmation message dialog starts here*@
        <div class="modal fade" id="dialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Success!</h4>
                    </div>
                    <div class="modal-body">
                        <span></span>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> Close</button>
                        @*<button type="button" class="btn btn-primary" onclick="SaveAddress();"><i class="glyphicon glyphicon-ok"></i> Yes</button>*@
                    </div>
                </div>
            </div>
        </div>

    @*<div id="deleteDialog" style="display:none;">Do you really want to Delete this Product Image?</div>*@
        @*Delete Dialog Modal Start *@
        <div class="modal fade" id="deleteDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Property Image</h4>
                    </div>
                    <div class="modal-body">
                        Do you really want to Delete this Product Image?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> No</button>
                        <button type="button" class="btn btn-primary" onclick="DeleteYes();"><i class="glyphicon glyphicon-ok"></i> Yes</button>
                    </div>
                </div>
            </div>
        </div>
        @*Delete Dialog Modal End *@

        <script language="Javascript" type="text/javascript">
            var _ProductID = @_ProductID;
            $(document).ready(function(){
                $('#fileProductImage').change(function () {
                    $('#ProductImage_Cosmetic').val($(this).val());
                });
                BindImageCropper();
                parent.ChildHideLoading();
            });
            function DeleteYes () {
                ShowLoadingAnimation(false);
                DeleteImage();               
                $('#deleteDialog').modal('hide');
            }
            function SetCoordinates(c) {
                $('#hdnCoordinates').val(c.x + ',' + c.y + ',' + c.w + ',' + c.h );
            }
            var _jCropApi;
            var _ActualWidth = 0;
            var _ActualHeight = 0;
            function BindImageCropper() {
                var widthAndHeight = $('#hdnWidthHeight').val();
                if(widthAndHeight.length > 0)
                {
                    if (_jCropApi) _jCropApi.destroy();
                    $('#imgCropBox').Jcrop({
                        setSelect: [0, 0, 200, 150],
                        onChange: ShowPreview,
                        onSelect: ShowPreview,
                        aspectRatio: @ConfigReader.ProductImageAspectRatio //1.33
                        }, function () {
                            _ActualWidth = widthAndHeight.split(',')[0];
                            _ActualHeight = widthAndHeight.split(',')[1];
                            _jCropApi = this;
                            parent.AdjustiFrameHeight($(document).height());
                        });
                }
                else
                    parent.AdjustiFrameHeight($(document).height());
            }

            function ShowPreview(coords) {
                SetCoordinates(coords);
                if (parseInt(coords.w) > 0 && _ActualWidth > 0 && _ActualHeight > 0) {
                    var rx = 140 / coords.w;
                    var ry = 105 / coords.h;

                    $('#imgPreview').css({
                        width: Math.round(rx * _ActualWidth) + 'px',
                        height: Math.round(ry * _ActualHeight) + 'px',
                        marginLeft: '-' + Math.round(rx * coords.x) + 'px',
                        marginTop: '-' + Math.round(ry * coords.y) + 'px'
                    });
                }
            }
            function CropAndSaveImage() {
                var coordinates =  $('#hdnCoordinates').val();
                if(coordinates.length > 0)
                {
                    var url = '@Url.Action("CropAndSaveImage", "ProductImage", new { area = AppConstants.Area.PRIVATE })';
                    var data = { ID: $('#hdnProductImageID').val(), ProductID: _ProductID, Picture: $('#imgCropBox').attr('src'), CropProperty: coordinates, OriginalFileName: $('#hdnOriginalFileName').val() }; //imageJson, //$.toJSON(image), //'fileName=Hydrangeas.jpg&cropProperty=' + $('#hdnCoordinates').val();
                    ShowLoadingAnimation(false);
                    Ajax(url, data, CropAndSaveImage_Success);
                }
                else                    
                    $('#dialog').modal('show').find('.modal-body span').html('Please Select and Upload an Image first to Set it as a Property Image.');
            }
            function CropAndSaveImage_Success(obj) {
                HideLoadingAnimation();
                var image = eval(obj);
                $('#divCropBoxContainer').hide();
                $('#imgPreview').hide();
                $('#btnSave').attr('disabled', true);

                var html = '<div class="rh-thumb-container">' +
                                '<div class="pull-left"><img src="' + image.Thumbnail + '" alt="" title="" /></div>' +
                                '<div class="pull-left"><button class="btn btn-danger btn-sm" onclick="ConformDeleteDialog(' + image.ID + ', this);" title="Click to Delete this Image."><i class="glyphicon glyphicon-remove"></i> </button></div>' +
                                '<div class="clearfix"></div>' +
                            '</div>';
                $('#divThumbContainer').append(html);
                $('#trUploadControls').slideDown('slow');
                $('#divButtons').fadeOut('slow');
                parent.UpdateImageList(image.Thumbnail, image.Picture);
                parent.AdjustiFrameHeight('iframeImageList');
            }
            function CancelImageCrop() {
                $('#divCropBoxContainer').slideUp('slow');
                $('#trUploadControls').slideDown('slow');
                $('#divButtons').fadeOut('slow');
                $('#imgPreview').fadeOut('slow');
                $('#hdnCoordinates').val('');
            }
            var _AnchorToDelete = null;
            var _ImageIdToDelete = 0;
            function ConformDeleteDialog(imageId, anchorElement) {
                _ImageIdToDelete = imageId;
                _AnchorToDelete = anchorElement;
                $('#deleteDialog').modal('show');//.dialog('open');
            }
            function DeleteImage() {
                var url = '@Url.Action("DeleteProductImage", "ProductImage", new { area = AppConstants.Area.PRIVATE })';
                var data = 'imageId=' + _ImageIdToDelete;
                Ajax(url, data, Delete_Success);
            }
            function Delete_Success(isDeleted) {
                if(isDeleted){
                    $('#divInfoMessage').html('');
                    var thumbUrl = $(_AnchorToDelete).parent().parent().find('img').attr('src');
                    $(_AnchorToDelete).closest('.rh-thumb-container').remove();
                    $('#dialog').modal('show').find('.modal-body span').html('Property Image Deleted Successfully.');//alert("Product Image Deleted Successfully.");
                    setTimeout(function () { $('#dialog').modal('hide'); }, 3000);
                    parent.AdjustiFrameHeight('iframeImageList');
                    parent.DeleteFromImageList(thumbUrl);
                }
                else
                    $('#dialog').modal('show').find('.modal-body span').html('Sorry! Requested Image was not found for Delete.');//alert("Sorry! Requested Image was not found for Delete.");
                HideLoadingAnimation();
            }
            function ValidateUpload() {
                if($('#fileProductImage').val().length > 0){
                    ShowLoadingAnimation(false);
                    $('#frmProductImage').submit();
                }
                else
                    return false;
                return true;
            }
        </script>
    }    
</div>

@section PageHeadSection{
    @Scripts.Render("~/bundles/jcropjsfull")
    <style type="text/css">
        .rh-crop-table{border-collapse:collapse; width:100%;} .rh-crop-table td{vertical-align:top;}
        .rh-crop-table tr:first-child td:first-child{border-left:#eeeeee 1px solid; height:460px;}
        /*td.tdLeft{min-height:490px;}*/
        div.rh-thumb-container{border-bottom:#efefef 0px solid; margin-bottom:10px;}
        div.rh-thumb-container button { margin: 1px 0px 0px -35px; }
    </style>
}


